package com.py.payment.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.py.payment.dto.ret.SiteNumericRetDto;
import com.py.payment.entity.PyIngredients;
import com.py.payment.entity.PySite;
import com.py.payment.entity.PySiteNumeric;
import com.py.payment.mapper.PySiteNumericMapper;
import com.py.payment.service.PyIngredientsService;
import com.py.payment.service.PySiteNumericService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.py.payment.service.PySiteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 站点成分预定值 服务实现类
 * </p>
 *
 * @author py
 * @since 2024-04-27
 */
@Service
public class PySiteNumericServiceImpl extends ServiceImpl<PySiteNumericMapper, PySiteNumeric> implements PySiteNumericService {

    @Autowired
    private PyIngredientsService ingredientsService;

    @Autowired
    private PySiteService siteService;

    @Override
    public SiteNumericRetDto getSiteNumericList() {
        SiteNumericRetDto siteNumeric = new SiteNumericRetDto();
        QueryWrapper<PyIngredients> ingredientsQueryWrapper = new QueryWrapper<>();
        ingredientsQueryWrapper.orderByAsc("id");
        List<PyIngredients> ingredientsList = this.ingredientsService.list(ingredientsQueryWrapper);
        List<String> ingredientsTitleList = ingredientsList.stream().map(PyIngredients::getTitle).toList();

        List<PySite> siteList = this.siteService.list();


        List<JSONObject> infoList = new ArrayList<>();

        siteList.forEach(s->{
            JSONObject info = new JSONObject();
            info.put("id", s.getId());
            info.put("siteTitle", s.getTitle());
            ingredientsList.forEach(item->{
                QueryWrapper<PySiteNumeric> siteNumericQueryWrapper = new QueryWrapper<>();
                siteNumericQueryWrapper.eq("site_id", s.getId());
                siteNumericQueryWrapper.eq("ingredient_id", item.getId());
                siteNumericQueryWrapper.orderByDesc("id");
                siteNumericQueryWrapper.last("limit 1");
                PySiteNumeric pySiteNumeric = this.getOne(siteNumericQueryWrapper);
                info.put(item.getTitle(),pySiteNumeric.getNumericValue());
            });
            infoList.add(info);
        });
        siteNumeric.setTitleList(ingredientsTitleList);
        siteNumeric.setInfoList(infoList);
        return siteNumeric;
    }
}
